<template>
  <div id="app">
    <van-submit-bar
      :disabled = "is_disabled"
      button-text="去支付"
      :button-type="isVisitorPrice ? 'buy-customer' : 'buy'"
      @submit="toPay"
    >
      <div class="submit-bar-left">
        总价：<span>￥<i>{{totalPrice}}</i></span> 
        <a href="javascript:;" @click="priceList">明细<i class="ucai-icon ucai-icon-xiasanjiao"></i></a>
      </div>
    </van-submit-bar>

    <!--费用明细 -->
    <van-popup
      v-model="show"
      closeable
      round
      close-icon="cross"
      position="bottom"
      :style="{height:'50%',bottom:'50px','padding-bottom':'50px', overflow:'hidden'}"
    >
      <div class="view-price">
        <h3>费用明细</h3>
        <div class="title">{{product_name}}</div>
        <ul class="cost-list">
          <li v-for="(item,index) in formData.skus" :key="index">
            <!--酒店明细-->
             <template v-if="product_kind==3">
              <template v-if="item.qty">
              <ul>
                <li class="hotel-title van-hairline--bottom"><span>{{item.sku_name}}</span></li> 
                <li v-for="(v,k) in multi_package_price[index]" :key="k">
                  <span>{{multi_package_date[k].substr(5,5)}}</span><i>￥{{v}} x {{item.qty}}</i>
                </li>
              </ul>
              </template>
             </template>
             <!--其他产品明细-->
             <template v-else>
              <ul class="mg-top-xs">
                <li class="sub-title">
                  <template v-if="item.qty"><span>{{item.sku_name}}</span><i>￥{{item.sale_price}} x {{item.qty}}</i></template>
                </li> 
              </ul>
             </template>
          </li>
        </ul>
      </div>
    </van-popup>

    <!--游客需出行人登录弹窗-->
    <traveler-login-popup :traveler_login.sync="is_traveler_login"/>

    <remote-js src="https://pv.sohu.com/cityjson?ie=utf-8" @load="loadIp"/>
  </div>
</template>


<script>
  import { 
    Icon,
    Field,
    CellGroup,
    Button,
    Toast,
    SubmitBar,
    Popup,
  } from "vant";
  import {
    submitForm,
  } from "@/api/modules/booking";
  import { mobileReg } from '@utils/regexp';
  import { getConfig } from '@/api/modules/index';
  import { 
    isLogin,
    getUserData,
    setSignIn,
    getSignInByKey,
    getStorageOpenid, 
  } from '@utils/storage_base_config'
  import { 
    login,
    getUserInfo
  } from '@/api/modules/user'

  import importJs from '@cmpt_com/importJs';
  import { getRolePrice } from '@utils/role'

  import travelerLoginPopup from '@views/booking/components/traveler-login-popup'
  export default {
    name: "pay-bar",
    data(){
        return {
          loginRole: '0', // 预定登录，固定游客角色

          is_traveler_login:false,
          border: false,
          mobileColor: false,
          codeColor: false,
          phone: getSignInByKey('account'),
          captcha:'',

          show: false,
          openid: '',
          is_disabled: false, //是否禁用提交按钮
          form_ver_flag:0, //表单验证标识
          form_limit_flag:0, //表单验证标识1[套餐最小、最大可购买数量]
          form_traveler_flag:0, //表单验证标识2[出行人信息]
          isVisitorPrice: getRolePrice() === '0', // 是否展示游客价
          secret: this.$getUrlParam('secret'), // 加密字符串
        }
    },

    components:{
      [Icon.name]: Icon,
      [Field.name]: Field,
      [CellGroup.name]: CellGroup,
      [Button.name]: Button,
      [Toast.name]: Toast,
      [SubmitBar.name]: SubmitBar,
      [Popup.name]: Popup,
      [importJs.name]: importJs,
      [travelerLoginPopup.name]: travelerLoginPopup
    },

    props: {
      product_kind:{
        type:Number
      },
      multi_package_price:{
        type:Array
      },
      multi_package_date:{
        type:Array
      },
      package_limit:{
       type: Object,
        default: () => {}
      },
      package_traveler:{
        type: Array
      },
      formData: {
        type: Object,
        default: () => {}
      },
      product_name:{
        type:String
      },
      traveler_type_name:{
        type: String
      },
      traveler_login:{
        type: Boolean,
        default:false
      },
    },

    computed: {
      //产品总价
      totalPrice() {
        var total = 0;
        var total_num = 0;
        let packageData = this.formData.skus;
        for(let item in packageData){
          let num = Number(packageData[item].qty);
          let price = this.multi_package_price[item].reduce(function(preVal,curVal){
            return parseFloat(preVal) + parseFloat(curVal);
          })
          if(!num){
            num = 0;
          }
          total_num += num;
          total += price * num;
        }
        total_num ? this.is_disabled = false : this.is_disabled = true;
        return total.toFixed(2);
      }
    },

    watch: {
      totalPrice(newVal) {
        this.$parent.formData.amount = newVal; //更新订单金额
        this.$parent.formData.should_pay = newVal; //更新订单实付金额
      },

      package_traveler(newVal){
        this.$nextTick(() => {
          if(!isLogin() && this.package_traveler.length){
            this.is_traveler_login = true;
          }
        })
      },

      is_traveler_login(newVal){
        this.$parent.traveler_login = newVal;
      }
    },

    created() {
      if(this.isVisitorPrice){
        this.openid = getStorageOpenid()
        this.getWxInfo();
      }
    },

    methods:{
      //价格明细
      priceList(){
        this.show = !this.show;
      },

      //保存当前地址以及ip
      loadIp(){
        if(!localStorage.local_ip){
          let local_ip = returnCitySN["cip"];
          localStorage.setItem('local_ip', local_ip)
          localStorage.setItem('local_city', returnCitySN["cname"])
          localStorage.setItem('local_zone_id', returnCitySN["cid"])
          this.$parent.formData.ip = local_ip||'';
        }
      },

      // 微信登录
      getWxInfo() {
        if (!this.$is_from_wx)
          return
        if(this.openid){
          this.wxLogin(this.openid)
          return
        }
        require.ensure(['@utils/wechat'], (require) => {
          const wechat = require('@utils/wechat')['default']
          const code = this.$getUrlParam('code')
          code ? wechat.getOpenid(code).then(res => {
            const openid = (res.data || {}).openid
            if(!openid)
              return
            this.openid = openid
            this.wxLogin(openid)
          }) : wechat.getCode()
        }, 'wechat')
      },

      // 游客微信 openid 登录
      async wxLogin(openid) {
        login({
          openid: openid,
          kind: Number(this.loginRole)
        }).then(res => {
          debugger
          setSignIn({
            ...res.data,
            role: this.role,
          })
          // 获取用户信息。强制刷新缓存。
          getUserData(true).finally(() => {
            //this.afterLogin(res)
          })
        }).catch(err => {
          debugger
        })
      },

      // 游客正常登录
      async login(formSubmitData) {
          login({
            kind: Number(this.loginRole),
            password: '',
            account: this.formData.contact_phone,
            captcha: this.formData.captcha,
            once_str: this.formData.once_str,
            openid: this.openid,
            secret: this.secret,
          }).then(res => {
            setSignIn({
              ...res.data,
              role: this.loginRole,
              account: this.formData.contact_phone
            })
            // 获取用户信息。强制刷新缓存。
            getUserData(true).finally(() => {
              this.submitOrder(formSubmitData);
            })
          }).catch(err => {
            setSignIn({
              account: this.formData.contact_phone
            })
          })
      },

      //提交订单
      async submitOrder(formSubmitData) {
        submitForm(formSubmitData)
          .then(res => {
              if(res.code==200){
                this.$goPage('payment', {
                  type: 1,
                  order_no:res.data.order_no
                })
              }  
          }).catch(err => {
            Toast(err.data.msg);
          })
      },

      //去支付
      toPay(){
        this.show = false;
        let nameReg  = /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/;
        let formSubmitData = this.formData ? JSON.parse(JSON.stringify(this.formData)): {};
        let package_name = "";

        //显示游客登录弹窗
        if(!isLogin() && this.isVisitorPrice && !this.is_traveler_login && this.package_traveler.length){
          this.is_traveler_login = true;
        }

        if(!formSubmitData.skus[0].avail_date){
          Toast("请选择使用日期");
          return;
        }

        jump:
        for(let i = 0, len = formSubmitData.skus.length; i < len; i++){
            //多套餐显示产品名称
            if(formSubmitData.skus.length>1){
              package_name = `[${formSubmitData.skus[i].sku_name}]`;
            }

            //验证最小、最大可购买数量
            if(this.package_limit.min[i]>0 && (formSubmitData.skus[i].qty < this.package_limit.min[i]) && formSubmitData.skus[i].qty){
              Toast(`${package_name}最少${this.package_limit.min[i]}张起预订`);
              this.form_limit_flag = 1;
              break;
            }
            else if(this.package_limit.max[i]>0 && (formSubmitData.skus[i].qty > this.package_limit.max[i]) && formSubmitData.skus[i].qty){
              Toast(`${package_name}最多只能预订${this.package_limit.max[i]}张`);
              this.form_limit_flag = 1;
              break;
            } 
            else{
              this.form_limit_flag = 0;

              //出行人验证
              if(formSubmitData.skus[i].id_real_type && formSubmitData.skus[i].qty){
                let package_len = 1;
                if(formSubmitData.skus[i].id_real_type==2){
                  package_len = formSubmitData.skus[i].qty;
                }

                for(let m = 0; m < package_len; m++){
                  let is_empty = 0;
                  if(formSubmitData.skus[i].travelers[m]){
                    is_empty = Object.keys(formSubmitData.skus[i].travelers[m]).length;
                  }

                  if(!is_empty){
                    Toast(`请填写${this.traveler_type_name}${m+1}${package_name}`);
                    this.form_traveler_flag = 1;
                    break jump;
                  }
                  else{
                    if(formSubmitData.skus[i].travelers[m].note){
                      Toast(`${this.traveler_type_name}${m+1}验证不通过${package_name}`);
                      this.form_traveler_flag = 1;
                      break jump;
                    }
                    else{
                      this.form_traveler_flag = 0;
                    } 
                  }
                }
              }

            }
 
        }
        
        if(this.form_traveler_flag || this.form_limit_flag){
          return;
        }
        else if(!formSubmitData.contact_name){
          Toast("请填写联系人");
          return;
        }
        else if(!nameReg.test(formSubmitData.contact_name)){
          Toast("请填写真实姓名");
          return;
        }
        else if(!formSubmitData.contact_phone){
          Toast("请填写手机号码");
          return;
        }
        else if(!mobileReg.test(formSubmitData.contact_phone)){
          Toast("请填写正确的手机号码");
          return;
        }

        //提交过滤数量为0的套餐数据
        formSubmitData.skus = formSubmitData.skus.filter(function(item){
          return item.qty!=0;
        });
        formSubmitData.secret = this.isVisitorPrice ? this.secret : ''
        
        //游客未登录【套餐无需出行人】
        if(!isLogin() && this.isVisitorPrice && !this.package_traveler.length){
            if(!formSubmitData.captcha){
              Toast("请填写验证码");
              return;
            }
            if(!formSubmitData.once_str){
              Toast("请重新获取验证码");
              return;
            }
            this.login(formSubmitData);
        }
        else{
          this.submitOrder(formSubmitData);//提交订单
        }

      }
    },

  }
</script>

<style lang="less" scoped>
@import "~@style_m/basic/utils/index";
.submit-bar-left{
  color: #999;
  font-size: 12px;
  text-align: left;
  padding-left: 10px;
  width: 100%;
  span{
    margin-right: 19px;
    color: @color-buy;
    i{
      font-size: 18px;
    }
  }
}
.van-button--danger{
    width: 125px;
    background-color: @color-main;
    border: 1px solid @color-main;
}
.van-button--disabled{
  border: solid 1px #ccc!important;
  background: #ccc!important;
  color: #999;
  opacity: 1;
}
.view-price{
  width: 100%;
  height: 100%;

  h3{
    text-align: center;
    line-height: 44px;
    font-size: 18px;
    font-weight: normal;
  }
  .title{
    font-size: 15px;
    line-height: 24px;
    position: relative;
    display: flex;
    box-sizing: border-box;
    width: 100%;
    padding: 2px 16px;
    overflow: hidden;
    background-color: #fff;
    span{
      flex: 1;
    }
    i{
      color: #333;
    }
  }

  .cost-list{
    height: 92%;
    overflow-y: auto;
    >li{
       margin-bottom:10px;
      li{
        position: relative;
        display: flex;
        box-sizing: border-box;
        width: 100%;
        padding: 0 16px;
        overflow: hidden;
        background-color: #fff;
        color: #999;
        line-height: 18px;
        font-size: 12px;
        span{
          flex: 1;
        }
        i{
          position: relative;
          overflow: hidden;
          color: #969799;
          text-align: right;
          vertical-align: middle;
        }
      }

      .sub-title{
         font-size: 14px;
      }

      .hotel-title{
        padding: 5px 16px;
        margin-bottom:5px;
        font-size: 14px;
        &:first-child{
          margin-top: 5px;
        }
        span{
          color: #666;
        }
      }

    }
  }

}

.traveler-login{
  padding: 0 25px 25px;
  max-width: 590px;
  border-radius: 8px;
  width: 80%;
  z-index: 9998!important;

  h3{
    text-align: center;
    line-height: 44px;
    font-size: 18px;
    font-weight: normal; 
  }
  .van-cell {
    padding-left: 0;
    padding-right: 0;
    font-size: 17px;
    margin: 13px 0;
    &:after, &:before {
        position: absolute;
        box-sizing: border-box;
        content: ' ';
        pointer-events: none;
        right: 0;
        bottom: 0;
        left: 0;
        border-bottom: 1px solid #ebedf0;
        transform: scaleY(1)
    }
    &:before {
      right: 100%;
      border-bottom-color: #444;
      transition: right ease .5s;
      z-index: 1;
    }
    &.active:before {
      right: 0;
    }
  }

  .van-button--default {
    border: none;
    border-left: 1px solid #f3f3f3;
    color: @color-main;
    &[disabled] {
        background: none!important;
        color: #ccc;
    }
  }
  .van-row--flex {
    color: #666;
    margin-top: 12.5px;
    font-size: 16px;
  }
  .van-button--small {
    height: 25px;
    line-height: 25px;
    border-radius: 0;
    font-size: @font-size-lg;
    padding-left: 15px;
    border-left-color: #e4e4e4;
  }
  a.van-button--disabled {
      color: #999!important;
      opacity: 1;
  }
}
</style>